from flask import Blueprint, request, jsonify, session
from functools import wraps
from typing import Any, Callable
from db_migration import get_db_connection

# 创建蓝图
annotation_replies_bp = Blueprint('annotation_replies', __name__)

def login_required(f: Callable) -> Callable:
    """登录装饰器"""
    @wraps(f)
    def decorated_function(*args: Any, **kwargs: Any) -> Any:
        if 'user_id' not in session:
            return jsonify({'error': '请先登录'}), 401
        return f(*args, **kwargs)
    return decorated_function

@annotation_replies_bp.route('/api/annotations/<int:annotation_id>/replies', methods=['GET'])
@login_required
def get_annotation_replies(annotation_id):
    """获取批注的所有回复"""
    try:
        conn = get_db_connection()
        
        # 检查批注是否存在
        annotation = conn.execute('SELECT id FROM annotations WHERE id = ?', (annotation_id,)).fetchone()
        if not annotation:
            conn.close()
            return jsonify({'error': '批注不存在'}), 404
        
        # 获取批注的所有回复
        replies = conn.execute('''
            SELECT r.*, u.username
            FROM annotation_replies r
            JOIN users u ON r.user_id = u.id
            WHERE r.annotation_id = ?
            ORDER BY r.created_at ASC
        ''', (annotation_id,)).fetchall()
        
        conn.close()
        return jsonify({'replies': [dict(r) for r in replies]})
    except Exception as e:
        print(f"获取批注回复错误: {e}")
        return jsonify({'error': f'获取批注回复失败: {str(e)}'}), 500

@annotation_replies_bp.route('/api/annotations/<int:annotation_id>/replies', methods=['POST'])
@login_required
def create_annotation_reply(annotation_id):
    """创建批注回复"""
    try:
        data = request.get_json(silent=True) or {}
        content = (data.get('content') or data.get('reply') or '').strip()
        
        if not content:
            return jsonify({'error': '回复内容不能为空'}), 400
        
        user_id = session['user_id']
        conn = get_db_connection()
        
        # 检查批注是否存在
        annotation = conn.execute('SELECT id FROM annotations WHERE id = ?', (annotation_id,)).fetchone()
        if not annotation:
            conn.close()
            return jsonify({'error': '批注不存在'}), 404
        
        # 创建回复
        cursor = conn.execute('''
            INSERT INTO annotation_replies (annotation_id, user_id, content)
            VALUES (?, ?, ?)
        ''', (annotation_id, user_id, content))
        
        reply_id = cursor.lastrowid
        conn.commit()
        
        # 获取创建的回复详情
        reply_data = conn.execute('''
            SELECT r.*, u.username
            FROM annotation_replies r
            JOIN users u ON r.user_id = u.id
            WHERE r.id = ?
        ''', (reply_id,)).fetchone()
        
        conn.close()
        return jsonify({'success': True, 'reply': dict(reply_data)})
    except Exception as e:
        print(f"创建批注回复错误: {e}")
        return jsonify({'error': f'创建批注回复失败: {str(e)}'}), 500

@annotation_replies_bp.route('/api/annotation-replies/<int:reply_id>', methods=['PUT'])
@login_required
def update_annotation_reply(reply_id):
    """更新批注回复"""
    try:
        data = request.get_json(silent=True) or {}
        content = (data.get('content') or data.get('reply') or '').strip()
        
        if not content:
            return jsonify({'error': '回复内容不能为空'}), 400
        
        user_id = session['user_id']
        conn = get_db_connection()
        
        # 检查回复是否存在且是否有权限修改
        reply_data = conn.execute('SELECT user_id FROM annotation_replies WHERE id = ?', (reply_id,)).fetchone()
        if not reply_data:
            conn.close()
            return jsonify({'error': '回复不存在'}), 404
        
        is_admin = session.get('is_admin', False)
        if reply_data['user_id'] != user_id and not is_admin:
            conn.close()
            return jsonify({'error': '无权限修改此回复'}), 403
        
        # 更新回复
        conn.execute('''
            UPDATE annotation_replies
            SET content = ?, updated_at = CURRENT_TIMESTAMP
            WHERE id = ?
        ''', (content, reply_id))
        conn.commit()
        
        # 获取更新后的回复详情
        updated_reply = conn.execute('''
            SELECT r.*, u.username
            FROM annotation_replies r
            JOIN users u ON r.user_id = u.id
            WHERE r.id = ?
        ''', (reply_id,)).fetchone()
        
        conn.close()
        return jsonify({'success': True, 'reply': dict(updated_reply)})
    except Exception as e:
        print(f"更新批注回复错误: {e}")
        return jsonify({'error': f'更新批注回复失败: {str(e)}'}), 500

@annotation_replies_bp.route('/api/annotation-replies/<int:reply_id>', methods=['DELETE'])
@login_required
def delete_annotation_reply(reply_id):
    """删除批注回复"""
    try:
        user_id = session['user_id']
        conn = get_db_connection()
        
        # 检查回复是否存在且是否有权限删除
        reply_data = conn.execute('SELECT user_id FROM annotation_replies WHERE id = ?', (reply_id,)).fetchone()
        if not reply_data:
            conn.close()
            return jsonify({'error': '回复不存在'}), 404
        
        is_admin = session.get('is_admin', False)
        if reply_data['user_id'] != user_id and not is_admin:
            conn.close()
            return jsonify({'error': '无权限删除此回复'}), 403
        
        # 删除回复
        conn.execute('DELETE FROM annotation_replies WHERE id = ?', (reply_id,))
        conn.commit()
        conn.close()
        
        return jsonify({'success': True})
    except Exception as e:
        print(f"删除批注回复错误: {e}")
        return jsonify({'error': f'删除批注回复失败: {str(e)}'}), 500